{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "d78f2240-5a8e-444d-bb4e-c3117b41a220",
   "metadata": {},
   "source": [
    "1. 数据预处理，将running的单位一致化\n",
    "2. 特征选择\n",
    "3. 模型训练和评估（暂且使用线性模型）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "447e2a07-3e02-4ee3-952e-414dc3dd948e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 1642 entries, 0 to 1641\n",
      "Data columns (total 10 columns):\n",
      " #   Column        Non-Null Count  Dtype  \n",
      "---  ------        --------------  -----  \n",
      " 0   model         1642 non-null   object \n",
      " 1   year          1642 non-null   int64  \n",
      " 2   motor_type    1642 non-null   object \n",
      " 3   running       1642 non-null   object \n",
      " 4   wheel         1642 non-null   object \n",
      " 5   color         1642 non-null   object \n",
      " 6   type          1642 non-null   object \n",
      " 7   status        1642 non-null   object \n",
      " 8   motor_volume  1642 non-null   float64\n",
      " 9   price         1642 non-null   int64  \n",
      "dtypes: float64(1), int64(2), object(7)\n",
      "memory usage: 128.4+ KB\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "(           model  year motor_type        running wheel    color   type  \\\n",
       " 0         toyota  2022     petrol       3000  km  left  skyblue  sedan   \n",
       " 1  mercedes-benz  2014     petrol     132000  km  left    black  sedan   \n",
       " 2            kia  2018     petrol   95000  miles  left    other  sedan   \n",
       " 3  mercedes-benz  2002     petrol  137000  miles  left   golden  sedan   \n",
       " 4  mercedes-benz  2017     petrol     130000  km  left    black  sedan   \n",
       " \n",
       "       status  motor_volume  price  \n",
       " 0  excellent           2.0  24500  \n",
       " 1  excellent           2.0  25500  \n",
       " 2  excellent           2.0  11700  \n",
       " 3  excellent           3.2  12000  \n",
       " 4       good           2.0  26000  ,\n",
       " None)"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "\n",
    "# 加载数据集\n",
    "file_path = 'train.csv'\n",
    "vehicle_data = pd.read_csv(file_path)\n",
    "vehicle_test_data = pd.read_csv(\"test.csv\")\n",
    "\n",
    "# Display the first few rows and basic information about the dataset\n",
    "vehicle_data.head(), vehicle_data.info()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b21484b6-ba08-4dcf-8b6f-d09a2e1ca890",
   "metadata": {},
   "source": [
    "数据预处理，里程单位转换"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "777e0a1f-e8b9-433f-912d-5cb719fb34e7",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.preprocessing import LabelEncoder\n",
    "\n",
    "# 预处理数据\n",
    "\n",
    "# Step 1: Convert the \"running\" column to a uniform unit (kilometers)\n",
    "# Extract numeric values and handle units (assuming 1 mile = 1.60934 km)\n",
    "def convert_to_km(value):\n",
    "    if \"miles\" in value:\n",
    "        return float(value.split()[0].replace(',', '')) * 1.60934  # convert miles to km\n",
    "    elif \"km\" in value:\n",
    "        return float(value.split()[0].replace(',', ''))  # already in km\n",
    "    return None\n",
    "\n",
    "vehicle_data['running_km'] = vehicle_data['running'].apply(convert_to_km)\n",
    "vehicle_test_data['running_km'] = vehicle_test_data['running'].apply(convert_to_km)\n",
    "\n",
    "# Drop the original \"running\" column as it is now redundant\n",
    "vehicle_data = vehicle_data.drop(columns=['running'])\n",
    "vehicle_test_data = vehicle_test_data.drop(columns=['running'])\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "70a350a5-8ddb-4f6a-af31-bdec85dd736e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>model</th>\n",
       "      <th>year</th>\n",
       "      <th>motor_type</th>\n",
       "      <th>wheel</th>\n",
       "      <th>color</th>\n",
       "      <th>type</th>\n",
       "      <th>status</th>\n",
       "      <th>motor_volume</th>\n",
       "      <th>price</th>\n",
       "      <th>running_km</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>toyota</td>\n",
       "      <td>2022</td>\n",
       "      <td>petrol</td>\n",
       "      <td>left</td>\n",
       "      <td>skyblue</td>\n",
       "      <td>sedan</td>\n",
       "      <td>excellent</td>\n",
       "      <td>2.0</td>\n",
       "      <td>24500</td>\n",
       "      <td>3000.000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>mercedes-benz</td>\n",
       "      <td>2014</td>\n",
       "      <td>petrol</td>\n",
       "      <td>left</td>\n",
       "      <td>black</td>\n",
       "      <td>sedan</td>\n",
       "      <td>excellent</td>\n",
       "      <td>2.0</td>\n",
       "      <td>25500</td>\n",
       "      <td>132000.000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>kia</td>\n",
       "      <td>2018</td>\n",
       "      <td>petrol</td>\n",
       "      <td>left</td>\n",
       "      <td>other</td>\n",
       "      <td>sedan</td>\n",
       "      <td>excellent</td>\n",
       "      <td>2.0</td>\n",
       "      <td>11700</td>\n",
       "      <td>152887.300</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>mercedes-benz</td>\n",
       "      <td>2002</td>\n",
       "      <td>petrol</td>\n",
       "      <td>left</td>\n",
       "      <td>golden</td>\n",
       "      <td>sedan</td>\n",
       "      <td>excellent</td>\n",
       "      <td>3.2</td>\n",
       "      <td>12000</td>\n",
       "      <td>220479.580</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>mercedes-benz</td>\n",
       "      <td>2017</td>\n",
       "      <td>petrol</td>\n",
       "      <td>left</td>\n",
       "      <td>black</td>\n",
       "      <td>sedan</td>\n",
       "      <td>good</td>\n",
       "      <td>2.0</td>\n",
       "      <td>26000</td>\n",
       "      <td>130000.000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1637</th>\n",
       "      <td>hyundai</td>\n",
       "      <td>2017</td>\n",
       "      <td>petrol</td>\n",
       "      <td>left</td>\n",
       "      <td>white</td>\n",
       "      <td>sedan</td>\n",
       "      <td>good</td>\n",
       "      <td>2.0</td>\n",
       "      <td>12400</td>\n",
       "      <td>193120.800</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1638</th>\n",
       "      <td>toyota</td>\n",
       "      <td>2014</td>\n",
       "      <td>petrol</td>\n",
       "      <td>left</td>\n",
       "      <td>black</td>\n",
       "      <td>sedan</td>\n",
       "      <td>good</td>\n",
       "      <td>2.0</td>\n",
       "      <td>16500</td>\n",
       "      <td>170000.000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1639</th>\n",
       "      <td>nissan</td>\n",
       "      <td>2018</td>\n",
       "      <td>petrol</td>\n",
       "      <td>left</td>\n",
       "      <td>blue</td>\n",
       "      <td>suv</td>\n",
       "      <td>good</td>\n",
       "      <td>2.0</td>\n",
       "      <td>19500</td>\n",
       "      <td>110883.526</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1640</th>\n",
       "      <td>nissan</td>\n",
       "      <td>2019</td>\n",
       "      <td>petrol</td>\n",
       "      <td>left</td>\n",
       "      <td>black</td>\n",
       "      <td>suv</td>\n",
       "      <td>excellent</td>\n",
       "      <td>2.0</td>\n",
       "      <td>19500</td>\n",
       "      <td>49889.540</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1641</th>\n",
       "      <td>toyota</td>\n",
       "      <td>2022</td>\n",
       "      <td>petrol</td>\n",
       "      <td>left</td>\n",
       "      <td>white</td>\n",
       "      <td>sedan</td>\n",
       "      <td>excellent</td>\n",
       "      <td>2.0</td>\n",
       "      <td>28500</td>\n",
       "      <td>20.000</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>1642 rows × 10 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "              model  year motor_type wheel    color   type     status  \\\n",
       "0            toyota  2022     petrol  left  skyblue  sedan  excellent   \n",
       "1     mercedes-benz  2014     petrol  left    black  sedan  excellent   \n",
       "2               kia  2018     petrol  left    other  sedan  excellent   \n",
       "3     mercedes-benz  2002     petrol  left   golden  sedan  excellent   \n",
       "4     mercedes-benz  2017     petrol  left    black  sedan       good   \n",
       "...             ...   ...        ...   ...      ...    ...        ...   \n",
       "1637        hyundai  2017     petrol  left    white  sedan       good   \n",
       "1638         toyota  2014     petrol  left    black  sedan       good   \n",
       "1639         nissan  2018     petrol  left     blue    suv       good   \n",
       "1640         nissan  2019     petrol  left    black    suv  excellent   \n",
       "1641         toyota  2022     petrol  left    white  sedan  excellent   \n",
       "\n",
       "      motor_volume  price  running_km  \n",
       "0              2.0  24500    3000.000  \n",
       "1              2.0  25500  132000.000  \n",
       "2              2.0  11700  152887.300  \n",
       "3              3.2  12000  220479.580  \n",
       "4              2.0  26000  130000.000  \n",
       "...            ...    ...         ...  \n",
       "1637           2.0  12400  193120.800  \n",
       "1638           2.0  16500  170000.000  \n",
       "1639           2.0  19500  110883.526  \n",
       "1640           2.0  19500   49889.540  \n",
       "1641           2.0  28500      20.000  \n",
       "\n",
       "[1642 rows x 10 columns]"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "vehicle_data"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "daea853b-f4f5-425d-9a3a-12b5517caff0",
   "metadata": {},
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "57de9451-32c6-4096-b3c2-3bbc085c1a23",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Step 2: Encode categorical variables using LabelEncoder\n",
    "label_encoders = {}\n",
    "categorical_columns = ['model', 'motor_type', 'wheel', 'color', 'type', 'status']\n",
    "\n",
    "for column in categorical_columns:\n",
    "    le = LabelEncoder()\n",
    "    vehicle_data[column] = le.fit_transform(vehicle_data[column])\n",
    "    label_encoders[column] = le  # save the encoder for reference\n",
    "    vehicle_test_data[column] = label_encoders[column].fit_transform(vehicle_test_data[column])\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "cd2cd1e7-9672-495a-849b-13ca8a397c4b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Step 3: Select features for the model\n",
    "features = vehicle_data[['model', 'year', 'motor_type','wheel', 'color',  'type', 'status', 'motor_volume', 'running_km']]\n",
    "target = vehicle_data['price']\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "1378fa7e-1d48-4124-bc51-3b6c91d6d0f5",
   "metadata": {},
   "outputs": [],
   "source": [
    "X_train=features\n",
    "y_train=target\n",
    "\n",
    "features_test = vehicle_test_data[['model', 'year', 'motor_type','wheel', 'color',  'type', 'status', 'motor_volume', 'running_km']]\n",
    "\n",
    "X_test=features_test\n",
    "y_test=pd.read_csv(\"sample_submission.csv\")[\"price\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "fa8df30e-7e42-4498-b40e-4e412516c532",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Split the data into training and test sets\n",
    "X_train, X_test, y_train, y_test = train_test_split(features, target, test_size=0.2, random_state=42)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "64761561-f3f7-4ebd-9256-f4f9d86e695c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(28813504.400094345, 0.4593690190053411)"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from sklearn.linear_model import LinearRegression\n",
    "from sklearn.metrics import mean_squared_error, r2_score\n",
    "\n",
    "# Train a simple linear regression model\n",
    "linear_model = LinearRegression()\n",
    "linear_model.fit(X_train, y_train)\n",
    "\n",
    "# Make predictions on the test set\n",
    "y_pred = linear_model.predict(X_train)\n",
    "\n",
    "# Evaluate the model using Mean Squared Error and R-squared metrics\n",
    "mse = mean_squared_error(y_train, y_pred)\n",
    "r2 = r2_score(y_train, y_pred)\n",
    "\n",
    "mse, r2\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b3294d65-afac-46a2-a38c-014991020309",
   "metadata": {},
   "source": [
    "# 模型优化"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 101,
   "id": "293f790d-5c24-4544-b614-6cd7742e6d2f",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.preprocessing import StandardScaler, PolynomialFeatures\n",
    "from sklearn.linear_model import LinearRegression\n",
    "from sklearn.pipeline import Pipeline\n",
    "from sklearn.metrics import mean_squared_error, r2_score\n",
    "import pandas as pd\n",
    "\n",
    "# 假设您的数据集已加载为 vehicle_data\n",
    "features = vehicle_data[['model', 'year', 'motor_type', 'wheel', 'color', 'type', 'status', 'motor_volume', 'running_km']]\n",
    "target = vehicle_data['price']\n",
    "X_train, X_test, y_train, y_test = train_test_split(features, target, test_size=0.2, random_state=42)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 102,
   "id": "63432abe-be36-4a4d-952a-d72f2ee21086",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style>#sk-container-id-2 {\n",
       "  /* Definition of color scheme common for light and dark mode */\n",
       "  --sklearn-color-text: black;\n",
       "  --sklearn-color-line: gray;\n",
       "  /* Definition of color scheme for unfitted estimators */\n",
       "  --sklearn-color-unfitted-level-0: #fff5e6;\n",
       "  --sklearn-color-unfitted-level-1: #f6e4d2;\n",
       "  --sklearn-color-unfitted-level-2: #ffe0b3;\n",
       "  --sklearn-color-unfitted-level-3: chocolate;\n",
       "  /* Definition of color scheme for fitted estimators */\n",
       "  --sklearn-color-fitted-level-0: #f0f8ff;\n",
       "  --sklearn-color-fitted-level-1: #d4ebff;\n",
       "  --sklearn-color-fitted-level-2: #b3dbfd;\n",
       "  --sklearn-color-fitted-level-3: cornflowerblue;\n",
       "\n",
       "  /* Specific color for light theme */\n",
       "  --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black)));\n",
       "  --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, white)));\n",
       "  --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black)));\n",
       "  --sklearn-color-icon: #696969;\n",
       "\n",
       "  @media (prefers-color-scheme: dark) {\n",
       "    /* Redefinition of color scheme for dark theme */\n",
       "    --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white)));\n",
       "    --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, #111)));\n",
       "    --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white)));\n",
       "    --sklearn-color-icon: #878787;\n",
       "  }\n",
       "}\n",
       "\n",
       "#sk-container-id-2 {\n",
       "  color: var(--sklearn-color-text);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 pre {\n",
       "  padding: 0;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 input.sk-hidden--visually {\n",
       "  border: 0;\n",
       "  clip: rect(1px 1px 1px 1px);\n",
       "  clip: rect(1px, 1px, 1px, 1px);\n",
       "  height: 1px;\n",
       "  margin: -1px;\n",
       "  overflow: hidden;\n",
       "  padding: 0;\n",
       "  position: absolute;\n",
       "  width: 1px;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-dashed-wrapped {\n",
       "  border: 1px dashed var(--sklearn-color-line);\n",
       "  margin: 0 0.4em 0.5em 0.4em;\n",
       "  box-sizing: border-box;\n",
       "  padding-bottom: 0.4em;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-container {\n",
       "  /* jupyter's `normalize.less` sets `[hidden] { display: none; }`\n",
       "     but bootstrap.min.css set `[hidden] { display: none !important; }`\n",
       "     so we also need the `!important` here to be able to override the\n",
       "     default hidden behavior on the sphinx rendered scikit-learn.org.\n",
       "     See: https://github.com/scikit-learn/scikit-learn/issues/21755 */\n",
       "  display: inline-block !important;\n",
       "  position: relative;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-text-repr-fallback {\n",
       "  display: none;\n",
       "}\n",
       "\n",
       "div.sk-parallel-item,\n",
       "div.sk-serial,\n",
       "div.sk-item {\n",
       "  /* draw centered vertical line to link estimators */\n",
       "  background-image: linear-gradient(var(--sklearn-color-text-on-default-background), var(--sklearn-color-text-on-default-background));\n",
       "  background-size: 2px 100%;\n",
       "  background-repeat: no-repeat;\n",
       "  background-position: center center;\n",
       "}\n",
       "\n",
       "/* Parallel-specific style estimator block */\n",
       "\n",
       "#sk-container-id-2 div.sk-parallel-item::after {\n",
       "  content: \"\";\n",
       "  width: 100%;\n",
       "  border-bottom: 2px solid var(--sklearn-color-text-on-default-background);\n",
       "  flex-grow: 1;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-parallel {\n",
       "  display: flex;\n",
       "  align-items: stretch;\n",
       "  justify-content: center;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  position: relative;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-parallel-item {\n",
       "  display: flex;\n",
       "  flex-direction: column;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-parallel-item:first-child::after {\n",
       "  align-self: flex-end;\n",
       "  width: 50%;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-parallel-item:last-child::after {\n",
       "  align-self: flex-start;\n",
       "  width: 50%;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-parallel-item:only-child::after {\n",
       "  width: 0;\n",
       "}\n",
       "\n",
       "/* Serial-specific style estimator block */\n",
       "\n",
       "#sk-container-id-2 div.sk-serial {\n",
       "  display: flex;\n",
       "  flex-direction: column;\n",
       "  align-items: center;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  padding-right: 1em;\n",
       "  padding-left: 1em;\n",
       "}\n",
       "\n",
       "\n",
       "/* Toggleable style: style used for estimator/Pipeline/ColumnTransformer box that is\n",
       "clickable and can be expanded/collapsed.\n",
       "- Pipeline and ColumnTransformer use this feature and define the default style\n",
       "- Estimators will overwrite some part of the style using the `sk-estimator` class\n",
       "*/\n",
       "\n",
       "/* Pipeline and ColumnTransformer style (default) */\n",
       "\n",
       "#sk-container-id-2 div.sk-toggleable {\n",
       "  /* Default theme specific background. It is overwritten whether we have a\n",
       "  specific estimator or a Pipeline/ColumnTransformer */\n",
       "  background-color: var(--sklearn-color-background);\n",
       "}\n",
       "\n",
       "/* Toggleable label */\n",
       "#sk-container-id-2 label.sk-toggleable__label {\n",
       "  cursor: pointer;\n",
       "  display: block;\n",
       "  width: 100%;\n",
       "  margin-bottom: 0;\n",
       "  padding: 0.5em;\n",
       "  box-sizing: border-box;\n",
       "  text-align: center;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 label.sk-toggleable__label-arrow:before {\n",
       "  /* Arrow on the left of the label */\n",
       "  content: \"▸\";\n",
       "  float: left;\n",
       "  margin-right: 0.25em;\n",
       "  color: var(--sklearn-color-icon);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 label.sk-toggleable__label-arrow:hover:before {\n",
       "  color: var(--sklearn-color-text);\n",
       "}\n",
       "\n",
       "/* Toggleable content - dropdown */\n",
       "\n",
       "#sk-container-id-2 div.sk-toggleable__content {\n",
       "  max-height: 0;\n",
       "  max-width: 0;\n",
       "  overflow: hidden;\n",
       "  text-align: left;\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-toggleable__content.fitted {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-toggleable__content pre {\n",
       "  margin: 0.2em;\n",
       "  border-radius: 0.25em;\n",
       "  color: var(--sklearn-color-text);\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-toggleable__content.fitted pre {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 input.sk-toggleable__control:checked~div.sk-toggleable__content {\n",
       "  /* Expand drop-down */\n",
       "  max-height: 200px;\n",
       "  max-width: 100%;\n",
       "  overflow: auto;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {\n",
       "  content: \"▾\";\n",
       "}\n",
       "\n",
       "/* Pipeline/ColumnTransformer-specific style */\n",
       "\n",
       "#sk-container-id-2 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-label.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Estimator-specific style */\n",
       "\n",
       "/* Colorize estimator box */\n",
       "#sk-container-id-2 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-estimator.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-label label.sk-toggleable__label,\n",
       "#sk-container-id-2 div.sk-label label {\n",
       "  /* The background is the default theme color */\n",
       "  color: var(--sklearn-color-text-on-default-background);\n",
       "}\n",
       "\n",
       "/* On hover, darken the color of the background */\n",
       "#sk-container-id-2 div.sk-label:hover label.sk-toggleable__label {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "/* Label box, darken color on hover, fitted */\n",
       "#sk-container-id-2 div.sk-label.fitted:hover label.sk-toggleable__label.fitted {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Estimator label */\n",
       "\n",
       "#sk-container-id-2 div.sk-label label {\n",
       "  font-family: monospace;\n",
       "  font-weight: bold;\n",
       "  display: inline-block;\n",
       "  line-height: 1.2em;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-label-container {\n",
       "  text-align: center;\n",
       "}\n",
       "\n",
       "/* Estimator-specific */\n",
       "#sk-container-id-2 div.sk-estimator {\n",
       "  font-family: monospace;\n",
       "  border: 1px dotted var(--sklearn-color-border-box);\n",
       "  border-radius: 0.25em;\n",
       "  box-sizing: border-box;\n",
       "  margin-bottom: 0.5em;\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-estimator.fitted {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "/* on hover */\n",
       "#sk-container-id-2 div.sk-estimator:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-2 div.sk-estimator.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Specification for estimator info (e.g. \"i\" and \"?\") */\n",
       "\n",
       "/* Common style for \"i\" and \"?\" */\n",
       "\n",
       ".sk-estimator-doc-link,\n",
       "a:link.sk-estimator-doc-link,\n",
       "a:visited.sk-estimator-doc-link {\n",
       "  float: right;\n",
       "  font-size: smaller;\n",
       "  line-height: 1em;\n",
       "  font-family: monospace;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  border-radius: 1em;\n",
       "  height: 1em;\n",
       "  width: 1em;\n",
       "  text-decoration: none !important;\n",
       "  margin-left: 1ex;\n",
       "  /* unfitted */\n",
       "  border: var(--sklearn-color-unfitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-unfitted-level-1);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link.fitted,\n",
       "a:link.sk-estimator-doc-link.fitted,\n",
       "a:visited.sk-estimator-doc-link.fitted {\n",
       "  /* fitted */\n",
       "  border: var(--sklearn-color-fitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-fitted-level-1);\n",
       "}\n",
       "\n",
       "/* On hover */\n",
       "div.sk-estimator:hover .sk-estimator-doc-link:hover,\n",
       ".sk-estimator-doc-link:hover,\n",
       "div.sk-label-container:hover .sk-estimator-doc-link:hover,\n",
       ".sk-estimator-doc-link:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "div.sk-estimator.fitted:hover .sk-estimator-doc-link.fitted:hover,\n",
       ".sk-estimator-doc-link.fitted:hover,\n",
       "div.sk-label-container:hover .sk-estimator-doc-link.fitted:hover,\n",
       ".sk-estimator-doc-link.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "/* Span, style for the box shown on hovering the info icon */\n",
       ".sk-estimator-doc-link span {\n",
       "  display: none;\n",
       "  z-index: 9999;\n",
       "  position: relative;\n",
       "  font-weight: normal;\n",
       "  right: .2ex;\n",
       "  padding: .5ex;\n",
       "  margin: .5ex;\n",
       "  width: min-content;\n",
       "  min-width: 20ex;\n",
       "  max-width: 50ex;\n",
       "  color: var(--sklearn-color-text);\n",
       "  box-shadow: 2pt 2pt 4pt #999;\n",
       "  /* unfitted */\n",
       "  background: var(--sklearn-color-unfitted-level-0);\n",
       "  border: .5pt solid var(--sklearn-color-unfitted-level-3);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link.fitted span {\n",
       "  /* fitted */\n",
       "  background: var(--sklearn-color-fitted-level-0);\n",
       "  border: var(--sklearn-color-fitted-level-3);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link:hover span {\n",
       "  display: block;\n",
       "}\n",
       "\n",
       "/* \"?\"-specific style due to the `<a>` HTML tag */\n",
       "\n",
       "#sk-container-id-2 a.estimator_doc_link {\n",
       "  float: right;\n",
       "  font-size: 1rem;\n",
       "  line-height: 1em;\n",
       "  font-family: monospace;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  border-radius: 1rem;\n",
       "  height: 1rem;\n",
       "  width: 1rem;\n",
       "  text-decoration: none;\n",
       "  /* unfitted */\n",
       "  color: var(--sklearn-color-unfitted-level-1);\n",
       "  border: var(--sklearn-color-unfitted-level-1) 1pt solid;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 a.estimator_doc_link.fitted {\n",
       "  /* fitted */\n",
       "  border: var(--sklearn-color-fitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-fitted-level-1);\n",
       "}\n",
       "\n",
       "/* On hover */\n",
       "#sk-container-id-2 a.estimator_doc_link:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "#sk-container-id-2 a.estimator_doc_link.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-3);\n",
       "}\n",
       "</style><div id=\"sk-container-id-2\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>Pipeline(steps=[(&#x27;scaler&#x27;, StandardScaler()),\n",
       "                (&#x27;poly_features&#x27;, PolynomialFeatures(include_bias=False)),\n",
       "                (&#x27;linear_regression&#x27;, LinearRegression())])</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item sk-dashed-wrapped\"><div class=\"sk-label-container\"><div class=\"sk-label fitted sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-2\" type=\"checkbox\" ><label for=\"sk-estimator-id-2\" class=\"sk-toggleable__label fitted sk-toggleable__label-arrow fitted\">&nbsp;&nbsp;Pipeline<a class=\"sk-estimator-doc-link fitted\" rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.5/modules/generated/sklearn.pipeline.Pipeline.html\">?<span>Documentation for Pipeline</span></a><span class=\"sk-estimator-doc-link fitted\">i<span>Fitted</span></span></label><div class=\"sk-toggleable__content fitted\"><pre>Pipeline(steps=[(&#x27;scaler&#x27;, StandardScaler()),\n",
       "                (&#x27;poly_features&#x27;, PolynomialFeatures(include_bias=False)),\n",
       "                (&#x27;linear_regression&#x27;, LinearRegression())])</pre></div> </div></div><div class=\"sk-serial\"><div class=\"sk-item\"><div class=\"sk-estimator fitted sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-3\" type=\"checkbox\" ><label for=\"sk-estimator-id-3\" class=\"sk-toggleable__label fitted sk-toggleable__label-arrow fitted\">&nbsp;StandardScaler<a class=\"sk-estimator-doc-link fitted\" rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.5/modules/generated/sklearn.preprocessing.StandardScaler.html\">?<span>Documentation for StandardScaler</span></a></label><div class=\"sk-toggleable__content fitted\"><pre>StandardScaler()</pre></div> </div></div><div class=\"sk-item\"><div class=\"sk-estimator fitted sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-4\" type=\"checkbox\" ><label for=\"sk-estimator-id-4\" class=\"sk-toggleable__label fitted sk-toggleable__label-arrow fitted\">&nbsp;PolynomialFeatures<a class=\"sk-estimator-doc-link fitted\" rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.5/modules/generated/sklearn.preprocessing.PolynomialFeatures.html\">?<span>Documentation for PolynomialFeatures</span></a></label><div class=\"sk-toggleable__content fitted\"><pre>PolynomialFeatures(include_bias=False)</pre></div> </div></div><div class=\"sk-item\"><div class=\"sk-estimator fitted sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-5\" type=\"checkbox\" ><label for=\"sk-estimator-id-5\" class=\"sk-toggleable__label fitted sk-toggleable__label-arrow fitted\">&nbsp;LinearRegression<a class=\"sk-estimator-doc-link fitted\" rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.5/modules/generated/sklearn.linear_model.LinearRegression.html\">?<span>Documentation for LinearRegression</span></a></label><div class=\"sk-toggleable__content fitted\"><pre>LinearRegression()</pre></div> </div></div></div></div></div></div>"
      ],
      "text/plain": [
       "Pipeline(steps=[('scaler', StandardScaler()),\n",
       "                ('poly_features', PolynomialFeatures(include_bias=False)),\n",
       "                ('linear_regression', LinearRegression())])"
      ]
     },
     "execution_count": 102,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 定义包含标准化和多项式特征的流水线\n",
    "poly_model = Pipeline([\n",
    "    ('scaler', StandardScaler()),\n",
    "    ('poly_features', PolynomialFeatures(degree=2, include_bias=False)),\n",
    "    ('linear_regression', LinearRegression())\n",
    "])\n",
    "\n",
    "# 训练模型\n",
    "poly_model.fit(X_train, y_train)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 103,
   "id": "22a9a5df-d716-499d-b678-07e5c467e2e9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "优化后的均方误差 (MSE): 21652426.25027074\n",
      "优化后的R²得分: 0.5079820187657746\n"
     ]
    }
   ],
   "source": [
    "# 预测并评估模型\n",
    "y_poly_pred = poly_model.predict(X_test)\n",
    "poly_mse = mean_squared_error(y_test, y_poly_pred)\n",
    "poly_r2 = r2_score(y_test, y_poly_pred)\n",
    "\n",
    "print(\"优化后的均方误差 (MSE):\", poly_mse)\n",
    "print(\"优化后的R²得分:\", poly_r2)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d9f5dee9-6624-4be9-a9f8-b64f5001188c",
   "metadata": {},
   "source": [
    "# 预测价格"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "0e4bb7b6-810f-4575-9230-599810130ae4",
   "metadata": {},
   "outputs": [],
   "source": [
    "test=vehicle_test_data[['model', 'year', 'motor_type', 'wheel', 'color', 'type', 'status', 'motor_volume', 'running_km']]\n",
    "sub=linear_model.predict(test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "22284f21-5782-43ea-ae26-9c8ef229d0f4",
   "metadata": {},
   "outputs": [],
   "source": [
    "sub=sub.astype(int)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "502d1a1d-3b53-49bd-bc9c-e9b03ec982b6",
   "metadata": {},
   "outputs": [],
   "source": [
    "pd_sub=pd.DataFrame(sub,columns=[ \"price\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "5fb9d0a8-ed2e-4d19-be4a-70085a86a868",
   "metadata": {},
   "outputs": [],
   "source": [
    "pd_sub.insert(0, 'Id',pd.Series(range(411)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "29786884-bac0-4160-9400-a586170e8544",
   "metadata": {},
   "outputs": [],
   "source": [
    "pd_sub.to_csv(\"submission.csv\", sep=',', index=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e0a9a8ea-e43f-438f-a9af-c3d134b81b38",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
